package com.anjho.dao;

import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

import com.anjho.pojo.Client;

@FacesConverter(value = "clientConverter")
public class DAOClient extends DAOGeneric implements Converter {

	private static final long serialVersionUID = -7622407981574104674L;

	public DAOClient() {
		super();
	}

	@SuppressWarnings("unchecked")
	public List<Client> getClientList() throws Exception {
		return (List<Client>) super.getList("Client.getClientList");
	}

	public Object getAsObject(FacesContext facesContext, UIComponent component,
			String submittedValue) {
		if (submittedValue.trim().equals("")) {
			return null;
		} else {
			try {
				long clcode = Long.parseLong(submittedValue);

				for (Client c : getClientList()) {
					if (c.getClcode() == clcode) {
						return c;
					}
				}

			} catch (Exception ex) {
				throw new ConverterException(new FacesMessage(
						FacesMessage.SEVERITY_ERROR, "Erro de conversão",
						"Cliente inválido"));
			}
		}
		return null;
	}

	public String getAsString(FacesContext facesContext, UIComponent component,
			Object value) {
		if (value == null || value.equals("")) {
			return "";
		} else {
			return String.valueOf(((Client) value).getClcode());
		}
	}

}
